 #define _CRT_SECURE_NO_WARNINGS 1

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* sortList(ListNode* head) {
        //处理特殊情况
        if (!head || !head->next) return head;

        //1.找到整个链表中心节点，将整个链表分成两个链表
        ListNode* mid = FindMid(head);
        ListNode* newhead = mid->next;
        mid->next = nullptr;

        //2.对两个链表进行排序，并进行连接
        ListNode* left = sortList(head);
        ListNode* right = sortList(newhead);
        return merge(left, right);
    }

    //此函数只适用2个及以上的节点
    ListNode* FindMid(ListNode* cur)
    {
        ListNode* slow = cur;
        ListNode* fast = cur;
        while (fast->next && fast->next->next)
        {
            fast = fast->next->next;
            slow = slow->next;
        }
        return slow;
    }

    //堆链表进行排序
    ListNode* merge(ListNode* l1, ListNode* l2)
    {
        if (!l1) return l2;
        if (!l2) return l1;
        if (l1->val <= l2->val)
        {
            l1->next = merge(l1->next, l2);
            return l1;
        }
        else
        {
            l2->next = merge(l1, l2->next);
            return l2;
        }
    }
};